import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);

export default {
  namespaced:true,
  state:{
    cartPlist:[],  // 购物车商品数组
    plist:JSON.parse(localStorage.getItem('cart-product')) || []
  },
  getters: {
  },
  mutations: {
    setCartPlist(state,payload){  // 修改state的状态
      state.cartPlist = payload
    },
    setPlist(state,payload){
      state.plist = payload
    },
    // 加入购物车
    addPlist(state,payload){
      let pobj = state.plist.find(item=>item.productId === payload.productId )
      if(pobj){
        Toast('已经有了');
      }else{
        Toast.success("加入成功")
        state.plist.unshift(payload)
        localStorage.setItem("cart-product",JSON.stringify(state.plist))
      }
    },

    delPitem(state){
      state.plist = state.plist.filter(item=>!item.free)
      localStorage.setItem("cart-product",JSON.stringify(state.plist))
    },
    // 加减操作
    additem(state,payload){
      state.plist[payload.idx].qty = state.plist[payload.idx].qty*1 + payload.symbol
    }

  },
  actions:{
    getCartPlist({commit}){  // 本地请求数据 , 提交mutations
      fetch("/json/cartProduct.json").then(res=>res.json()).then(res=>{
       commit("setCartPlist",res.shppingbagList)
       let arr = [] // 把商品整合到同一个数组
       for(let i=0;i<res.shppingbagList.length;i++){
         for(let j=0;j<(res.shppingbagList[i].multiPromotions[0].singlePromotions[0].cartViewItems.length);j++){
           arr.push(res.shppingbagList[i].multiPromotions[0].singlePromotions[0].cartViewItems[j])
          }
        }
      localStorage.setItem("cart-product",JSON.stringify(arr))
      commit("setPlist",arr)
      })
    }
  }
}
